<template>
    <div class="goodsContatin">

        <div id="forward" class="mui-popover mui-popover-action mui-popover-bottom">
			<div class="mui-table-view accountList">
				 <div class="mui-scroll-wrapper">
                    <div class="mui-scroll">
                        <div class="confirmGoods" v-for="(item,index) in buyList" :key="index" v-show="item.count>0">
                            <div class="title">{{item.goods.name}}</div>
                            <div class="totalPrice">¥{{item.goods.price*item.count}}</div>
                            <div class="foodsNum">
                                <num-select class="numSelectTotal"  :initCount="item.count" @add="countAdd($event,item.goods)" @subtraction="countSubtraction($event,item.goods)" :goodsId="item.goods.id" :buyList="buyList"></num-select>
                            </div>
                        </div>
                    </div>
                </div>
			</div>
			<ul class="mui-table-view zhanwei">
            
			</ul>
		</div>



        <div class=" fullscreen">
            <!-- 左边表格 -->
			<div  id="leftTab_out">
				<div id="leftTab" >
                    <div class="item leftItem" v-for="goodsData in goodsDataList" :typeId="goodsData.id" :key="goodsData.id" :class="{'tabActive':istabActive==goodsData.id}" @click="leftClick(goodsData.id)">
                        <span class="buyNumTip">{{butTypeList[goodsData.id]}}</span>
                        <span>{{goodsData.name}}</span>
                    </div>
				</div>
			</div>
            <!-- 右边表格 -->
			<div id="rightTab"  >
                <div id="rightTab_in" @scroll="rightWheel">
                    <div class="itemShell" v-for="goodsList in goodsDataList" :key="goodsList.id" :typeId="goodsList.id" >
                        <div class="itemHead"  :class="{'topType':isTopType==goodsList.id,'topType_move':isTopType_move==goodsList.id}" :typeId="goodsList.id">
                            {{goodsList.name}}
                        </div>


                        <div class="item"  v-for="goodsItem in goodsList.goods" :key="goodsItem.id" >
                            <div class="foodsContext">
                                <div class="foodsImg">
                                    <img :src="goodsItem.img" alt="">
                                </div>

                                <div class="foodsInfo">
                                    <div class="title">{{goodsItem.name}}</div>
                                    <div class="description">{{goodsItem.description}}</div>
                                    <div class="sales">月售{{goodsItem.monthSales}}份</div>
                                    <div class="price">
                                        <div class="priceShow">{{goodsItem.price}}</div>

                                        <div class="addButton">
                                            <num-select @add="countAdd($event,goodsItem)" @subtraction="countSubtraction($event,goodsItem)" :goodsId="goodsItem.id" :buyList="buyList"></num-select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
			</div>
		</div>

        <div class="bottomDiv">
            <div class="price" @click="showAccount">{{total | totalFilter}}</div>
            <div class="accountButton" @click="accountClick()">结算</div>
        </div>


      
        
    </div>    
</template>

<script>
import { Toast } from 'mint-ui';
import mui from "../../lib/mui/js/mui.min.js"

export default {
    data(){
        return {
            restautId:null,
            restautName:null,
            goodsDataList:[],
            updateData:false,
            goodsTypeData:[],
            istabActive:0,
            isTopType:0, 
            isTopType_move:-1,
            lastTopType:0,
            
            buyList:{},//选中要购买的商品列表
            butTypeList:{},//每个类型买了多少统计
            total:0,

            rightTop:{}, //右边的位置数据 {类型id:到顶部的偏移位置}
            rightTop_twoTree:[], //用于方便二分查找的容器 [[区间头，区间尾],[区间头，区间尾]，[区间头，区间尾]]

            leftTop:{}, //左边的位置数据同rightTop

            isSetScoller:false, //是不是手动设置右边滑轮的位置

            leftScrollHeightMax:null, //左边最大能滚动的距离
            leftClientHeight:null, //左边可以看到的最大高度
        }
    },
    created(){
        //this.initData();
        this.restautId = this.$route.query.id;
        this.restautName = this.$route.query.name;
        this.initGoodsData();
    },
    mounted(){
        //initCom() 
        //mui.init();
         mui('.mui-scroll-wrapper').scroll({
        //     scrollY: true, //是否竖向滚动
        // indicators: true, //是否显示滚动条
         })
    },
    updated(e){
        if(this.updateData){
            this.updateData = false;
            this.initScrollDataRight();
            this.initScrollDataLeft();
        }
       
    },
    methods:{
        countAdd(count,goodsInfo){
            let id = goodsInfo["id"];
            let typeId = goodsInfo["goodsType"]
            let c = {
                goods:goodsInfo,
                count:count
            }

            let buyType = this.butTypeList[typeId];
            let typeCount = 1;
            if(buyType!=null){
                typeCount = buyType+1;
            }

            this.$set(this.buyList,id,c)
            this.$set(this.butTypeList,typeId,typeCount)
            this.totalCount();
            //this.buyList[id] = c;
        },
        countSubtraction(count,goodsInfo){
            let id = goodsInfo["id"];
            let typeId = goodsInfo["goodsType"]
            let c = {
                goods:goodsInfo,
                count:count
            }

            let buyType = this.butTypeList[typeId];
            let typeCount = null;
            if(buyType!=null){
                typeCount = buyType - 1;
                if(typeCount<=0){
                    typeCount=null;
                }
            }

            this.$set(this.buyList,id,c)
            this.$set(this.butTypeList,typeId,typeCount)
            this.totalCount();
        },
        initData(){
            let  goodsType =[]; 
            let  goods = [];
            for(i=0;i<40;i++){
                let gt = {
                    id:i,
                    name:`选项卡${i}`
                }
                goodsType.push(gt);
                let count = rnd(3,10)
                let gsArr = [];
                let gs = {
                    typeId:i,
                    goodsList:gsArr,
                }
                for(let b=0;b<count;b++){
                    let n = ""+i+b;
                    let bc ={
                        id:n,
                        name:`内容选项卡${n}`
                    }
                    gsArr.push(bc)
                }
                goods.push(gs)
            }
            this.goodsTypeData = goodsType;
            this.goodsData = goods;
        
        
        },
        initGoodsData(){
            let restautId = this.$route.query.id;
            let url =  `goods/get/${restautId}`;
            this.$http.get(url).then(res=>{
                let body = res.body;
                if(!body.success){
                    Toast(body.msg);
                    return;
                }
                let data = body.data;
                this.goodsDataList = data;
                this.updateData = true;
                if(data.length>0){
                    let firstId= data[0].id;
                    this.istabActive=firstId;
                    this.isTopType=firstId;
                    this.lastTopType=firstId;
                }

            })
        },
        initScrollDataRight(){
            let itemShelles = document.getElementsByClassName("itemShell");
            let fisrt = true;
            let two_tree = [];
            this.rightTop_twoTree = [];
            let last = null;
            let next = null;
            for(itemShell of itemShelles){
                let offsetTop = itemShell.offsetTop;
                let typeId =  itemShell.attributes.typeId.value;
                if(fisrt){
                     offsetTop = 0;
                     fisrt = false;
                }
                this.rightTop[typeId] = offsetTop;

                let twoItem = {
                    id:typeId,
                    value:offsetTop,
                }

                if(last == null){
                    last = twoItem
                }else{
                    next = twoItem;
                }

                if(next != null){
                    let arr = [last,next];
                    this.rightTop_twoTree.push(arr);
                    last = next;
                    next = null;
                }
            }
        },
        initScrollDataLeft(){
            let leftItems = document.getElementsByClassName("leftItem");
            for(leftItem of leftItems){
                let offsetTop = leftItem.offsetTop;
                let typeId =  leftItem.attributes.typeId.value;
                this.leftTop[typeId] = offsetTop;
            }
            this.leftClientHeight = document.querySelector("#leftTab").clientHeight;
            this.leftScrollHeightMax = document.querySelector("#leftTab").scrollHeight - this.leftClientHeight;
        },

        leftClick(id){
            //this.istabActive=id;
            let rightTop = this.rightTop[id];

           // this.isTopType = id
           // this.lastTopType= id;
            document.querySelector("#rightTab_in").scrollTop = rightTop;
           // this.isSetScoller = true;

        },
        rightWheel(e){
            if(this.isSetScoller){
                this.isSetScoller = false;
                return
            }

            let scrollTop = e.target.scrollTop;
            let ourPace = this.findTop(scrollTop);
            if(ourPace == null){
                return
            }
            let paceStart = ourPace[0]; //开始区间
            let paceEnd = ourPace[1];   //结束曲线
            
            let paceStart_id = paceStart["id"]; 

            if(this.lastTopType != paceStart_id){
                this.isTopType = paceStart_id
                this.lastTopType= paceStart_id;
                this.istabActive =  paceStart_id;
                
                let itemTop = this.leftTop[paceStart_id];
                let curTop = document.querySelector("#leftTab").scrollTop;


                if(itemTop < curTop ){
                    document.querySelector("#leftTab").scrollTop = curTop - this.leftClientHeight
                }else if(itemTop > curTop+this.leftClientHeight){
                    document.querySelector("#leftTab").scrollTop = curTop + this.leftClientHeight
                }
                return
             }


            let endValue = paceEnd["value"];
            let asc  = endValue - scrollTop;
            if(asc <20){
                this.isTopType_move =  paceStart_id;
                document.getElementsByClassName("topType")[0].style.top =  `${-(20-asc)}px`
            }else{
                 this.isTopType_move =  -1;
                document.getElementsByClassName("topType")[0].style.top =  null;
            }
            


        },
        /**
         * 二分查找数字所在区间
         */
        findTop(num,range){
             let len = this.rightTop_twoTree.length;
            if(range == null){
                range = [0,len-1];
            }
            //拿到本次需要判断区间的索引
            let index = parseInt((range[0]+range[1])/2);
            //拿到区间对象+
            let qj = this.rightTop_twoTree[index]
            //比较
            let last = qj[0]["value"];
            let next= qj[1]["value"];

             let new_range = null;
            if(num < last){
                new_range = [range[0],index-1];
            }else if(num >= next){
                new_range = [index+1,range[1]];
            }else{
                return qj;
            }
            
            if(new_range[0] > len-1 || new_range[1] < 0){
                return null;
            }
            return this.findTop(num,new_range);  
        },
        totalCount(){
           let buyList = this.buyList;
           let total = 0;
            for(goodsKey in buyList){
                if(isNaN(goodsKey)){
                    continue;
                }
                let buy = buyList[goodsKey];
                let count = buy["count"];
                let price = buy["goods"]["price"];
                total = total+count*price;
            }
            this.total = total.toFixed(2);
            
        },
        showAccount(){
            mui('#forward').popover('toggle');
        },
        accountClick(){
            let data = {
                orderData:this.buyList,
                resturantId:this.restautId,
                resturantName:this.restautName
            }
            let sec = new Date().getTime()
            const key = `order${sec}`;
            sessionStorage.setItem(key,JSON.stringify(data));
            this.$router.push({
                name:"confirmOrder",
                query:{
                    key:key
                }
            });
        },

    },
    computed:{
        buyNumTipHandle(){
            return function(id){
                let count = this.butTypeList[id];
                if(goods == null){
                    return "0"
                }
                return goods.count;
            }
        }
    },
    filters:{
        totalFilter(data){
            if(data == null || data==0){
                return "还未购买商品";
            }
            return `已购买:￥${data}`;
        },
    }
}


 function rnd(n, m){
        var random = Math.floor(Math.random()*(m-n+1)+n);
        return random;
}

</script>


<style scoped>

.leftItem{
    position: relative;
}
.buyNumTip{
   position: absolute;
    right: .8vw;
    top: .8vw;
    color: #fff!important;
    background-image: linear-gradient(-90deg,#ff7416,#ff3c15 98%);
    border-radius: 2vw;
    font-weight: 700;
    text-align: center;
    min-width: 3.733333vw;
    padding: 0 1.066667vw;
    line-height: 3.733333vw;
}

#leftTab{
    height: 100%;
    overflow: auto;
}

#rightTab {
   padding-left: 3vw;
}

 #rightTab_in{
      padding-top:20px;
       height: 100%;
       overflow: auto;
       
   }


#leftTab .item{
    width: 100%;
   
    font-size: 12px;
    line-height: 12px;
    background-color: #f8f8f8;
    padding: 4.666667vw 2vw;
    
}
#leftTab .item span{
    line-height: 1.2em;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    text-align: left;
    color: #666;
}



#rightTab .item{
    width: 100%
}


  .fullscreen #leftTab .tabActive{
        background-color: #fff;
    }

   .itemHead{
       height: 20px;
       font-size: 12px;
       color: #666;
       font-weight: bold;
       background-color: #fff;
   } 

  
   .fullscreen{
    
    height: 100%;
    display: flex;
    position: relative;
   } 
   .goodsContatin{
       height: 100%;
   }
  

</style>

<style lang="less" scoped>
    

    .confirmGoods{

        height: 27px;
        display: flex;
        padding-left: 20px;
        padding-right: 15px;
        margin-top:10px;
        .title{
           height: 100%; 
           width: 54vw;
            color: #000;
            font-size: 16px;
            text-align: left;
        }
        .totalPrice{
            height: 100%; 
             width: 15vw;
             color: red;
        }
        .foodsNum{
            height: 100%; 
             width: 20vw;
            .numSelectTotal{
                float:right;

            }
        }

    }


    #forward{
        //    height: 150px;
        // overflow: auto;
        // background-color: #fff;
        // opacity: 1;
        left: 0px;
        z-index: 899;

        
        .zhanwei{
            //width: 100%;
            height: 50px;
            opacity: 0;
            margin: 0px;
        }
        .accountList{
            //height: 150px;
           // width: 100%;
            height: 230px;
            background-color: #fff;
            overflow: auto;
            margin: 0px;
        }
    }

  


    .foodsContext{
        padding: 2.666667vw 0;
        margin-bottom: .133333vw;
        display: flex;
        min-height: 27.466667vw;
        position: relative;

        .foodsImg{
            width: 25.333333vw;
            height: 25.333333vw;
            -webkit-flex: none;
            flex: none;
            margin-right: 2.666667vw;
            position: relative;
            img{
                width: 100%;
            }
        }
        .foodsInfo{
            -webkit-flex: 1;
            flex: 1;
            position: relative;
            padding-bottom: 6.666667vw;
            padding-right: 4vw;
            .title{
                font-weight: 700;
                overflow: hidden;
                font-size: 16px;
                white-space: nowrap;
                width: 40vw;
                text-overflow: ellipsis;
            }
            .description{
                margin: 1.333333vw 0;
                color: #999;
                overflow: hidden;
                width: 42.666667vw;
                font-size: 10px;
                line-height: 14px;
            }
            .sales{
                margin: 2.733333vw 0!important;
                color: #999;
                font-size: 10px;
                line-height: 1;
                min-height: 1em;
            }
            .price{
                position: absolute;
                bottom: 0;
                margin-right: .266667vw;
                display: flex;
                justify-content: space-between;
                width: calc(~"100% - 3vw");
                
                .priceShow{
                     color: red;
                    line-height: 4.266667vw; 
                    font-family: PingFang SC,Helvetica Neue,Arial,sans-serif;
                }
                .priceShow:before{
                        content: "\A5";
                        font-size: .373333rem;
                        display: inline-block;
                    }
            }
        }
    }



     .topType{
        position:absolute;
        width: 100%;
        top: 0;
        z-index: 800;
       
    }

      .fullscreen{
        height: 100%;
        height: calc(~"100% - 55px");
        position: relative;
    }

    .bottomDiv{
        height: 55px;
        position: flex;
        bottom: 0px;
        z-index: 900;
        position: relative;
        .price{
            height: 100%;
            width: calc(~"100% - 100px");
            float: left;
            background-color: #695b5b;
            color: #fff;
            line-height: 55px;
            text-align: center;
            font-weight: bold;
        }
        .accountButton{
            float: left;
            height: 100%;
            width: 100px;
            text-align: center;
            font-weight: bold;
            color: #fff;
            line-height: 55px;
            background-color: #4fb52d;
            
        }
    }

    #leftTab_out{
        width: 20.5333vw;
    }
    
    #rightTab{
        width: calc(~"100% - 22.5333vw");
        position: relative;
    }

</style>


<style >
    #segmentedControls .mui-control-item{
        width: 100%;
    }

    #mainHead{
        position: relative;
        z-index: 999;
    }

    .mui-popover-action2{
            bottom: 0;
            width: 100%;
            -webkit-transition: -webkit-transform .3s,opacity .3s;
            transition: transform .3s,opacity .3s;
            -webkit-transform: translate3d(0,100%,0);
            transform: translate3d(0,100%,0);
            border-radius: 0;
            background: 0 0;
            -webkit-box-shadow: none;
            box-shadow: none;
            
    }
      .mui-backdrop{
         z-index: 898 !important;
    }


</style>

